import React from 'react';
import { View, ImageBackground, TouchableWithoutFeedback, FlatList } from 'react-native';
import { Flex, Toast, Modal } from 'antd-mobile-rn';
import Scene from '../screen/scene';
import { Navigation } from 'react-native-navigation';
import { createStyles } from '../../utils/view';
import NormalHeader from '../../components/NormalHeader';
import CText from '../../components/CText';
import GoodsItem from './components/goodsItem';
import Storage from '../../utils/storage';
import { connect } from 'react-redux';
import authActions from '../../controllers/auth/actions';
import { getIcoList, joinIco } from '../../service/ico';

const status_arr = [{
  id: 0,
  text: '预约中',
}, {
  id: 1,
  text: '进行中'
}, {
  id: 2,
  text: '已结束'
}
];

class IcoScreen extends React.Component {
  static navigatorStyle = {
    navBarHidden: true,
    navBarNoBorder: true,
  };

  constructor(props) {
    super(props);
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent.bind(this));
    this.state = {
      activeStatus: 1,
      slideValue: 0,
      list: [],
      ndate: 0,
      loading: false,
    };
  }

  onNavigatorEvent(event) {
    if (event.type === 'ScreenChangedEvent') {
      if (event.id === 'didAppear') {
        // this.timer = setInterval(
        //   () => { this.setState({ ndate: new Date() }) },
        //   1000
        // );
        this.init();
      }
      if (event.id === 'willDisappear') {
        this.timer && clearInterval(this.timer);
      }
    }
  }

  init = async () => {
    const token = await Storage.load('token');
    const { activeStatus } = this.state;
    if (token) {
      this.setState({ loading: true });
      const data = await getIcoList({ token, status: activeStatus });
      console.log('ico', data);
      if (data.code === 0) {
        this.setState({
          list: data.data,
          loading: false,
        });
      } else {
        this.setState({ loading: false, });
        Toast.fail(data.msg);
        if (data.code === -1) {
          // 用户过期
          this.props.Logout();
        }
      }
    } else {
      this.setState({ loading: false, });
      Navigation.showModal({
        screen: 'Login',
        title: '登录',
        passProps: {},
        animated: true,
        animationType: 'slide-horizontal',
        navigatorStyle: {},
        navigatorButtons: {},
      });
    }
  }

  // 参加众筹
  joinIco = async ({ size, cfid }) => {
    const token = await Storage.load('token');
    if (token) {
      const data = await joinIco({ token, size, cfid });
      if (data.code === 0) {
        this.setState({
          loading: false,
        });
        Toast.success(data.msg);
      } else {
        this.setState({ loading: false, });
        Toast.fail(data.msg);
        if (data.code === -1) {
          // 用户过期
          this.props.Logout();
        }
      }
    } else {
      this.setState({ loading: false, });
      Navigation.showModal({
        screen: 'Login',
        title: '登录',
        passProps: {},
        animated: true,
        animationType: 'slide-horizontal',
        navigatorStyle: {},
        navigatorButtons: {},
      });
    }
  }

  changeStatus = (activeStatus) => {
    this.state.activeStatus = activeStatus;
    this.init();
  }

  render() {
    const { list, ndate, loading } = this.state;
    return (
      <Scene isLoading={loading}>
        <NormalHeader>众筹</NormalHeader>
        <Flex style={styles.status_box} direction="row" justify="between" align="center" >
          {
            status_arr.map((status, index) => {
              if (this.state.activeStatus === status.id) {
                return (
                  <ImageBackground key={status.id} style={styles.status_item} source={require('../../assets/img/home/btn_buy.png')} resizeMode="cover">
                    <View style={styles.status_item_child}>
                      <CText color="#5F4601">{status.text}</CText>
                    </View>
                  </ImageBackground>
                );
              } else {
                return (
                  <TouchableWithoutFeedback key={status.id} onPress={() => this.changeStatus(status.id)}>
                    <View style={styles.status_item}>
                      <CText color="#5F4601">{status.text}</CText>
                    </View>
                  </TouchableWithoutFeedback>
                );
              }
            })
          }
        </Flex>
        <View style={styles.line}></View>
        <FlatList
          data={list}
          renderItem={({ item }) => <GoodsItem ndate={ndate} joinIco={this.joinIco} data={item} />}
          keyExtractor={(item, index) => `${item.id}`}
          extraData={ndate}
        />
      </Scene>
    );
  }
}

let styles = {
  status_box: {
    height: 88,
    paddingHorizontal: 58,
  },
  status_item: {
    width: 168,
    height: 56,
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: '#CC9900',
    borderRadius: 28,
  },
  line: {
    height: 30,
    backgroundColor: 'rgb(245,245,245)',
  }
};

styles = createStyles(styles);
export default connect((Store) => {
  return { };
}, { Logout: authActions.Logout })(IcoScreen);